package com.lee.mysql.service;

import com.lee.mysql.dao.TableDbInfoDao;
import com.lee.mysql.pojo.TableDbInfo;
import com.lee.mysql.util.DecryptUtil;
import com.lee.mysql.util.IdGenUtil;
import com.lee.mysql.util.JasyptEncryptUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.UUID;

/**
 * 数据库信息
 */
@Slf4j
@Service
@Transactional
@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)
public class TableDbInfoService {
    @Autowired
    private TableDbInfoDao tableDbInfoDao;



    /** 检测同一配置下是否存在源数据库 */
    public int checkMasterDb(String configId,String id){
        return tableDbInfoDao.checkMasterDb(configId,id);
    }

    /** [数据同步类型]检测同一配置下是否存在目标数据库 */
    public int checkTargetDb(String configId){
        return tableDbInfoDao.checkTargetDb(configId);
    }

    /** 获取配置信息条数 */
    public int getDbInfoTotal(String configId){
        return tableDbInfoDao.getDbInfoTotal(configId);
    }

    /** 新增数据库信息 */
    public int addRecord(TableDbInfo record){
        record.setId(IdGenUtil.flakeId());

        String deCodeB64 = DecryptUtil.deCodeB64(record.getDbPassword().trim());

        // 加密数据库密码
        String salt = UUID.randomUUID().toString();
        String pwd = JasyptEncryptUtils.encryptionPwd(deCodeB64, salt);

        record.setDbSalt(salt);
        record.setDbPassword(pwd);

        return tableDbInfoDao.insertOne(record);
    }

    /** 根据ID修改记录 */
    public int updateOneById(TableDbInfo record){

        String deCodeB64 = DecryptUtil.deCodeB64(record.getDbPassword().trim());

        // 加密数据库密码
        String salt = UUID.randomUUID().toString();
        String pwd = JasyptEncryptUtils.encryptionPwd(deCodeB64, salt);

        record.setDbSalt(salt);
        record.setDbPassword(pwd);

        return tableDbInfoDao.updateById(record);
    }

    /** 根据ID删除记录 */
    public int deleteById(String id){
        return tableDbInfoDao.deleteById(id);
    }


    /** 根据配置ID查询数据库列表 */
    public List<TableDbInfo> queryByConfigId(String configId){

        List<TableDbInfo> list = tableDbInfoDao.queryByConfigId(configId);
        list.forEach(db->{
            String pwd = JasyptEncryptUtils.decryptPwd(db.getDbPassword(), db.getDbSalt());
            db.setDbPassword(pwd);
        });

        return list;
    }


    /** 根据配置ID查询数据库列表并加密 */
    public List<TableDbInfo> queryByConfigIdEnCode(String configId){

        List<TableDbInfo> list = tableDbInfoDao.queryByConfigId(configId);
        list.forEach(db->{
            String pwd = JasyptEncryptUtils.decryptPwd(db.getDbPassword(), db.getDbSalt());
            db.setDbPassword(DecryptUtil.enCodeB64(pwd));
        });

        return list;
    }


}
